package com.tencent.qcloud.tim.demo.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.tencent.qcloud.tim.demo.R;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;

import com.tencent.qcloud.tim.demo.TIMAppService;
import com.tencent.qcloud.tim.demo.bean.UserInfo;
import com.tencent.qcloud.tim.demo.config.AppConfig;
import com.tencent.qcloud.tim.demo.main.MainActivity;
import com.tencent.qcloud.tim.demo.main.MainMinimalistActivity;
import com.tencent.qcloud.tim.demo.signature.GenerateTestUserSig;
import com.tencent.qcloud.tim.demo.utils.DBHelper;
import com.tencent.qcloud.tim.demo.utils.DemoLog;
import com.tencent.qcloud.tim.demo.utils.TUIUtils;
import com.tencent.qcloud.tuicore.interfaces.TUICallback;
import com.tencent.qcloud.tuicore.util.ToastUtil;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = LoginActivity.class.getSimpleName();
    private EditText etPhone, etPassword;
    private AppCompatButton btnLogin;
    private CheckBox cbUserAgreement;  // 用户协议复选框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        etPhone = findViewById(R.id.etPhone);
        etPassword = findViewById(R.id.etCode);
        btnLogin = findViewById(R.id.btnLogin);
        cbUserAgreement = findViewById(R.id.UserAgreement);  // 获取复选框视图
        // 初始化数据库

        // 设置手机号的 TextWatcher 实时校验
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
                // 不需要处理
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                // 每次文本改变时校验手机号
                String phone = charSequence.toString();


                if (phone.length() == 11) {
                    // 当手机号长度为11位时，校验手机号格式
                    if (!Patterns.PHONE.matcher(phone).matches()) {
                        etPhone.setError("请输入有效的手机号码");
                    }
                } else if (phone.length() > 11) {
                    // 限制最多输入11位
                    etPhone.setText(phone.substring(0, 11));
                    etPhone.setSelection(11);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                // 不需要处理
            }
        });

        // 设置密码输入框的监听，校验手机号
        etPassword.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {  // 当密码框失去焦点时进行校验
                String phone = etPhone.getText().toString().trim();
                if (phone.length() != 11) {
                    Toast.makeText(this, "手机号必须为11位", Toast.LENGTH_SHORT).show();
                } else if (!Patterns.PHONE.matcher(phone).matches()) {
                    Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                performLogin();
            }
        });
    }

    public void goRegisterLink(View view) {
        // 跳转到注册页面
        Intent intent = new Intent(LoginActivity.this, ZhuCeActivity.class);
        startActivity(intent);
    }

    private void performLogin() {
        String phone = etPhone.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 检查用户协议是否勾选
        if (!cbUserAgreement.isChecked()) {
            Toast.makeText(this, "请先勾选用户协议", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查手机号是否为空
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查手机号是否为11位
        if (phone.length() != 11) {
            Toast.makeText(this, "手机号必须为11位", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查手机号格式是否有效
        if (!Patterns.PHONE.matcher(phone).matches()) {
            Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查密码是否为空
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        // 使用子线程进行数据库验证和登录操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                int res;
                try {
                    res = DBHelper.checkUserAccount(phone, password);
                    if (res == 1) {
                        // 这里是在后台线程中，初始化IM SDK并进行登录
                        TIMAppService.getInstance().initBeforeLogin(0);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                btnLogin.setEnabled(false);
                            }
                        });

                        final String userID = etPhone.getText().toString();
                        final String userSig = GenerateTestUserSig.genTestUserSig(etPhone.getText().toString());

                        LoginWrapper.getInstance().loginIMSDK(LoginActivity.this, AppConfig.DEMO_SDK_APPID, userID, userSig, TUIUtils.getLoginConfig(), new TUICallback() {
                            @Override
                            public void onError(final int code, final String desc) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtil.toastLongMessage(getString(R.string.failed_login_tip) + ", errCode = " + code + ", errInfo = " + desc);
                                        btnLogin.setEnabled(true);
                                    }
                                });
                                DemoLog.i(TAG, "imLogin errorCode = " + code + ", errorInfo = " + desc);
                            }

                            @Override
                            public void onSuccess() {
                                UserInfo.getInstance().setUserId(userID);
                                UserInfo.getInstance().setUserSig(userSig);
                                UserInfo.getInstance().setAutoLogin(true);
                                UserInfo.getInstance().setDebugLogin(true);

                                // 登录成功，跳转到主页面
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Intent intent;
                                        if (AppConfig.DEMO_UI_STYLE == AppConfig.DEMO_UI_STYLE_CLASSIC) {
                                            intent = new Intent(LoginActivity.this, MainActivity.class);
                                        } else {
                                            intent = new Intent(LoginActivity.this, MainMinimalistActivity.class);
                                        }
                                        startActivity(intent);

                                        TIMAppService.getInstance().registerPushManually();

                                        finish();
                                    }
                                });
                            }
                        });

//                        // 设置手机号为用户ID
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                etPhone.setText(UserInfo.getInstance().getUserId());
//                            }
//                        });

                        System.out.println("登录成功");
                    } else if (res == -1) {
                        System.out.println("用户密码错误");
                    } else if (res == -2) {
                        System.out.println("用户不存在");
                    } else {
                        System.out.println("连接错误");
                    }
                } catch (Exception e) {
                    System.out.println("连接数据库失败");
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
    // 短信登录按钮点击事件
    public void onSmsLoginClick(View view) {
        // 假设你需要打开短信验证码输入的界面
        Intent intent = new Intent(LoginActivity.this, MobSMSActivity.class);
        startActivity(intent);
    }
}
